package com.owlsmart.bluecat.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.owlsmart.bluecat.R;
import com.owlsmart.bluecat.activity.BrowserActivity;
import com.owlsmart.bluecat.adapter.MovieListAdapter;
import com.owlsmart.bluecat.api.Api;
import com.owlsmart.bluecat.api.ApiConfig;
import com.owlsmart.bluecat.api.Constant;
import com.owlsmart.bluecat.api.TitleCallback;
import com.owlsmart.bluecat.entity.BaseSubjects;
import com.owlsmart.bluecat.entity.Subjects;
import com.owlsmart.bluecat.listener.OnItemChildClickListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;


public class MovieListFragment extends BaseFragment implements OnItemChildClickListener {
    private final String TAG = "VideoFragment";
    // 用来装标题，滑动的
    private String title;

    private String tag;

    // 起始数据
    public int pageStart;

    private List<Subjects> mData;
    // 刷新使用的属性
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;

    // 声明适配器变量
    private MovieListAdapter movieListAdapter;

    // 全局布局管理器，兼容播放器的
    private LinearLayoutManager linearLayoutManager;

    // 消息队列实现，在主线程中刷新UI
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    movieListAdapter.setDatas(mData);
                    // 通知recycleView刷新页面
                    movieListAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    // 无参构造器，方便下面new创建实例
    public MovieListFragment() {

    }


    // 把这个MovieListFragment放到每个滑块中去
    public static MovieListFragment newInstanceTitle(String title) {
        MovieListFragment fragment = new MovieListFragment();
        fragment.title = title;
        return fragment;
    }


    @Override
    protected int initLayout() {
        return R.layout.fragment_movie_list;
    }

    //初始化控件View
    @Override
    protected void initView() {

        recyclerView = mRootView.findViewById(R.id.movie_list_recycleView);
        // 刷新插件
        refreshLayout = mRootView.findViewById(R.id.movie_list_refreshLayout);
    }

    @Override
    protected void initDate() {
        //创建布局管理器， getActivity()获取父控件（fragment获取父activity控件对象）,HomeActivity
        linearLayoutManager = new GridLayoutManager(getActivity(), 3);
        // 设置方向 垂直
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        // 设置布局管理器为linearLayoutManager
        recyclerView.setLayoutManager(linearLayoutManager);

        // 创建适配器，为了绑定数据到控件上面
        movieListAdapter = new MovieListAdapter(getActivity());
        // 绑定完了，就把这个适配器设置一下
        recyclerView.setAdapter(movieListAdapter);
        // 设置点击事件
        movieListAdapter.setOnItemClickListener(new MovieListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Subjects mSubjects) {
                showToast("点击了");

                String url = mSubjects.getUrl();
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                bundle.putString("title",mSubjects.getTitle());
                navigateToWithBundle(BrowserActivity.class, bundle);
            }
        });

        // 设置刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                // 每次刷新，首页
                pageStart = 0;
                // 调用刷新的方法并且设置为true
                getMovieListData(true);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                // 加载，不需要刷新
                // refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                // 每次加载 pageNum++
                //每次叠加，相当于pageStart = pageStart + 10
                pageStart += 10;
                getMovieListData(false);
                // Log.d(TAG, "第页码数字" + pageNum);

            }
        });

        getMovieListData(true);
    }

    private void getMovieListData(final boolean isRefresh) {
        HashMap<String, Object> params = new HashMap<>();
        // params.put("type", "movie");
        params.put("sort", "recommend");
        params.put("tag", title);
        params.put("page_limit", Constant.pageLimit);
        params.put("page_start", pageStart);
        Api.assembleDoubanParams(ApiConfig.END_MOVIE, params).getRequest(getActivity(), new TitleCallback() {
            @Override
            public void onSuccess(final String res) {

                if (isRefresh) {
                    refreshLayout.finishRefresh(true); //如果是刷新，关闭下拉刷新动画
                } else {
                    refreshLayout.finishLoadMore(true); // 关闭动画
                }

                // Log.d(TAG, "请求返回值" + res);
                BaseSubjects baseSubjects = new Gson().fromJson(res, BaseSubjects.class);
                // Log.d(TAG, "映射返回值结果 = " + baseSubjects.getSubjects().get(0).getCover());
                if (baseSubjects != null && baseSubjects.getSubjects().size() > 0) {
                    List<Subjects> subjectsLists = baseSubjects.getSubjects();
                    if (subjectsLists != null && subjectsLists.size() > 0) {
                        // Log.d(TAG, "mData = " + mData.get(0).getCover());
                        // 在主线程中刷新UI
                        if (isRefresh) {
                            mData = subjectsLists;
                        } else {
                            mData.addAll(subjectsLists);
                        }
                        mHandler.sendEmptyMessage(0);

                    } else {
                        if (isRefresh) {
                            // 换成异步toast就可以不操作UI了
                            // showToast("加载无数据");
                            showToastSync("加载无数据");
                        } else {
                            showToastSync("没有更多数据了");
                        }
                    }
                }
            }

            @Override
            public void onFailure(Exception e) {
                // 接口请求失败，关闭动画
                if (isRefresh) {
                    refreshLayout.finishRefresh(true); //如果是刷新，关闭下拉刷新动画
                } else {
                    refreshLayout.finishLoadMore(true); // 关闭动画
                }
            }
        });

    }

    @Override
    public void onItemChildClick(int position) {

    }
}